import h5py


class GenericHdf:

    def __init__(self, file_path):
        self.file_path = file_path
        self.file = h5py.File(file_path, 'r')
        pass

    def __del__(self):
        self.file.close()
        self.file = None
        pass

    def __getitem__(self, key):
        if isinstance(key, int) and key >= 0:
            key = list(self.file.keys())[key]
        return self.file[key]

    def print(self):
        def print_group(name, obj):
            # 计算缩进级别
            level = name.count('/')
            # 打印缩进和名称
            print('  ' * level + name)
            for key, val in obj.attrs.items():
                print('  ' * (level + 1) + '{}: {}'.format(key, val))

        self.file.visititems(print_group)
        pass
